﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Net;
using System.Text;
using System.Web;
using System.Web.Http.Controllers;
using System.Web.Http.Filters;

namespace S1.Filters
{
    /// <summary>
    /// 基础身份验证过滤器
    /// </summary>
    public class BasicAuthenticationAttribute : ActionFilterAttribute
    {
        protected string Username { get; set; }
        protected string Password { get; set; }

        public BasicAuthenticationAttribute(string username, string password)
        {
            Username = username;
            Password = password;
        }

        public override void OnActionExecuting(HttpActionContext filterContext)
        {
            var req = filterContext.Request;
            var auth = req.Headers.Authorization;
            if (auth?.Scheme == "Basic")
            {
                // staff:BCLyon2024
                var cred = Encoding.UTF8.GetString(Convert.FromBase64String(auth.Parameter)).Split(':');
                var user = new { Name = cred[0], Pass = cred[1] };
                if (user.Name == Username && user.Pass == Password) return;
            }
            filterContext.Response = new HttpResponseMessage(HttpStatusCode.Unauthorized);
            filterContext.Response.Headers.Add("WWW-Authenticate", string.Format("Basic realm=\"{0}\"", "BasicRealm"));
        }
    }
}